/**
 * 
 */
package com.feib.stms.action;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.support.ResourceBundleMessageSource;

import com.feib.stms.model.Group;
import com.feib.stms.model.Securities;
import com.feib.stms.pagination.PaginatedList;
import com.feib.stms.service.GroupService;
import com.feib.stms.util.StmsUtil;
import com.feib.stms.util.UserUtil;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.integration.spring.SpringBean;

/**
 * @author Jimmy Liu
 *
 */
public class GroupActionBean  extends BaseActionBean 
{
	private static final long serialVersionUID = 7670238600734397390L;
	
	private static final String DEFAULT_JSP = "/WEB-INF/views/group/group.jsp";

    @SpringBean("groupService")
    private GroupService groupService;

	@SpringBean("messageSource")
	protected ResourceBundleMessageSource messageSource;
	
	private Group qryGroup;
	
	private Group editGroup;
	
	/**
	 * 訊息-畫面顯示用
	 */
	protected String message;
	
	private List<Securities> securities;
	
	private static Map<String, String> SORT_FIELD_NAMES = new LinkedHashMap<String, String>();
	static{
		SORT_FIELD_NAMES.put("groupNo", "GROUP_NO"); // 券商代號
		SORT_FIELD_NAMES.put("groupName", "GROUP_NAME"); // 名稱
	}
	

    /**
     * 券商查詢結果
     */
    private PaginatedList<Group> queryResult;
	
	@DefaultHandler
    public Resolution doDefault()
    {
        logger.debug("Enter doDefault mehtod.");
        return new ForwardResolution(DEFAULT_JSP);
    }
	
	public Resolution doQuery()
	{
		logger.debug("Enter doQuery mehtod.");
		try {
            //如果不是銀行端，則查詢條件要加入帳單業者限制
            if (!UserUtil.isBankGroup())
            {
                this.message = messageSource.getMessage("no.authority", null, "無權限查詢！", this.getContext().getRequest().getLocale());
                return new ForwardResolution(DEFAULT_JSP);
            }
            
            PaginatedList<Group> qryCondition = new PaginatedList<Group>();
    		
    		/* 設定換頁、排序等條件*/
    		String sortCriterion = null == queryResult ? null : queryResult.getSortCriterion();
    		List<String> sortFields = getSortFields();
    		if (StringUtils.isEmpty(sortCriterion) || null == getSortFieldNames().get(sortCriterion)) // 未設定/找不到 排序條件時候，則以存款帳號為主要排序
    			sortCriterion = sortFields.get(0);
    		
    		
    		if (null != queryResult)
    		{
    			qryCondition.setPageNumber(queryResult.getPageNumber());
    			qryCondition.setPageSize(queryResult.getPageSize());
    			qryCondition.setSortCriterion(getSortFieldNames().get(sortCriterion));
    			qryCondition.setSortDirection(queryResult.getSortDirection());
    		}
    		

    		if (null == queryResult || StringUtils.isEmpty(queryResult.getSortCriterion()) || !sortFields.contains(queryResult.getSortCriterion()))
    		{
    			// 以存款帳號由大到小排序
    			qryCondition.setSortCriterion(getSortFieldNames().get(sortFields.get(0)));
    			qryCondition.setSortDirection(PaginatedList.SORT_DIRECTION_DESC);
    		}

            //USER未輸入查詢條件，所以查詢物件會是NULL(查詢物件不可為NULL)
            if (null == qryGroup)
                qryGroup = new Group();

            //呼叫服務查詢
            queryResult = groupService.queryByGroupExcludeBank(qryGroup, qryCondition);
            
            if (null == queryResult)
			{
				this.message = messageSource.getMessage("query.nothing", null, "查無資料！", this.getContext().getRequest().getLocale());
				queryResult = new PaginatedList<Group>(); 
				queryResult.setPageNumber(qryCondition.getPageNumber());
				queryResult.setPageSize(qryCondition.getPageSize());
			}
			
			this.queryResult.setSortCriterion(sortCriterion);
			this.queryResult.setSortDirection(qryCondition.getSortDirection());
        }
        catch (Exception e) {
            logger.error("券商查詢錯誤:", e);
            this.message = ""; //TODO
        }

        return new ForwardResolution(DEFAULT_JSP);
	}
	
	public Resolution doQuerySecurities()
	{
		logger.debug("Enter doQuerySecurities mehtod.");
		editGroup = this.groupService.getByGroupPk(qryGroup.getGroupPk());
		securities = StmsUtil.getInstance().getSecuritiesByGroupPk(editGroup.getGroupPk());        
		return doQuery();
	}
	
	public void setNavigator()
	{
		if (null != queryResult)
		{
			int sortDirection = queryResult.getSortDirection();  //2 : ascending, else: descending
			String sortSpan = "<span class=\"ui-icon ui-icon-circle-triangle-n\"></span>"; //由小到大
			if (1 == sortDirection)
			{
				sortSpan = "<span class=\"ui-icon ui-icon-circle-triangle-s\"></span>"; //由大到小
			}
			
			String sortCriterion = queryResult.getSortCriterion();
			if (null!= sortCriterion && null != getSortFieldNames().get(sortCriterion))
			{
				this.getContext().getRequest().setAttribute(sortCriterion+"SortedClass", 1==sortDirection?"sortDesc":"sortAsc");
				this.getContext().getRequest().setAttribute(sortCriterion+"SortedSpan", sortSpan);
			}
			else
			{
				sortCriterion = getSortFields().get(0);
				this.getContext().getRequest().setAttribute(sortCriterion+"SortedClass", 1==sortDirection?"sortDesc":"sortAsc");
				this.getContext().getRequest().setAttribute(sortCriterion+"SortedSpan", sortSpan);
			}
			
	
			// 上下頁鈕處理
			int lastPageNumber = queryResult.getTotalPageCount();
			int currentPageNumber = queryResult.getPageNumber();
			int prePageNumber = currentPageNumber - 1;
			int nextPageNumber = currentPageNumber + 1;
			
			this.getContext().getRequest().setAttribute("lastPageNumber", new Integer(lastPageNumber));
			this.getContext().getRequest().setAttribute("currentPageNumber", new Integer(currentPageNumber));
			this.getContext().getRequest().setAttribute("prePageNumber", new Integer(prePageNumber));
			this.getContext().getRequest().setAttribute("nextPageNumber", new Integer(nextPageNumber));
		}
	}

	protected Map<String, String> getSortFieldNames(){
		return SORT_FIELD_NAMES;
	}
	
	public List<String> getSortFields()
	{
		List<String> result = new ArrayList<String>();
		CollectionUtils.addAll(result, getSortFieldNames().keySet().iterator()	);
		return result;
	}
	
	public Resolution doAjaxGroupNoChange()
	{
		return null;
	}

	public Group getQryGroup() {
		return qryGroup;
	}

	public void setQryGroup(Group qryGroup) {
		this.qryGroup = qryGroup;
	}

	public PaginatedList<Group> getQueryResult() {
		return queryResult;
	}

	public void setQueryResult(PaginatedList<Group> queryResult) {
		this.queryResult = queryResult;
	}

	public String getMessage() {
		return message;
	}
	
	/**
	 * 只顯示使用者可以查詢的母/分公司
	 * @return
	 */
	public List<Securities> getSecurities() {
		return securities;
	}

	public Group getEditGroup() {
		return editGroup;
	}

	public void setEditGroup(Group editGroup) {
		this.editGroup = editGroup;
	}

}
